//
//  SEGSanyDoorBaseViewController.m
//  Commom
//
//  Created by Clavis on 2019/8/28.
//

// VC
#import "SEGSanyDoorBaseViewController.h"
#import "SEGOpenDoorNoticeChooseViewController.h"
// View
#import "SEGAlertView.h"
#import "SEGHAllDoorView.h"
#import "SEGSanyQRCodeView.h"
// Model
#import "SEGOpenDoorBussinessManager.h"
// ViewModel
#import <SEGViewModel/SEGDoorListViewModel.h>

#define kHeaderViewHeight LYDistanceH(40.0)
#define kTopTabAreaHeight (kHeaderViewHeight + 44 + LYStatusBarHeight())

@interface SEGSanyDoorBaseViewController ()

@property (nonatomic, strong) UIButton *switchListButton;
@property (nonatomic, strong) UIButton *switchQRCodeButton;
@property (nonatomic, strong) SEGSanyQRCodeView *qrcodeView;
@property (nonatomic, strong) SEGHAllDoorView *otherDoorView;
@property (nonatomic, assign) BOOL isHaveTab; ///< 是否有tab页
@property (nonatomic, strong) SEGNewMyDoorListModel *oneQrcodePassDoor; ///< 海康门禁数据
@property (nonatomic, strong) NSArray<SEGNewMyDoorListModel*> *otherDoorList; ///< 其他数据
@property (nonatomic, strong) SEGDoorListViewModel *doorListViewModel;
@property (nonatomic, assign) CGFloat currentBrightness; // 保存当前的屏幕亮度
@property (nonatomic, assign) BOOL isChangedBrightness; // 保存是否进行过亮度修改

@end

@implementation SEGSanyDoorBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navDisplayType = SEGNavigationBarDisplayTypeHide;
    // 提交开门记录
    [self.doorListViewModel submitOpenDoorHistory];
    self.currentBrightness = [UIScreen mainScreen].brightness;
    
    if (self.needLoadDoorData) {
        // 需要先加载数据再展示界面
        [SVProgressHUD show];
        [[self.doorListViewModel requestNetAllDoorList] subscribeNext:^(id  _Nullable x) {
            [SVProgressHUD dismiss];
            [self setupUI];
        }];
    } else {
        [self setupUI];
    }
}

- (void)setupUI {
    self.title = @"";
    self.view.backgroundColor = kColor_W;
    
    // 判断是否存在一码通行门禁(已在外部请求了新门禁数据)
    self.oneQrcodePassDoor = [self.doorListViewModel getOneQrcodePassDoor];
    self.otherDoorList = [self.doorListViewModel getLocalAllDoorListExceptOneQrcodePassDoor];
    
    if (self.oneQrcodePassDoor) {
        if (self.otherDoorList.count > 0) {
            // 一码通行和其他门禁都存在 则显示tab
            self.isHaveTab = YES;
            [self creatOtherDoorView];
            [self creatTab];
        }
        // 没有其他门禁 只显示一码通行二维码
        WeakSelf;
        self.qrcodeView.retryBlock = ^{
            [weakSelf loadOneQRCodePassData];
        };
        [self.view addSubview:self.qrcodeView];
        [self.qrcodeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
            make.top.mas_equalTo(kTopTabAreaHeight);
        }];
        [self loadOneQRCodePassData];
        [self creatBackButton];
    } else {
        // 没有一码通行 显示默认门禁列表
        [self creatOtherDoorView];
    }
}

- (void)creatBackButton {
    // 添加返回按钮
    UIImage* image = [UIImage imageWithContentsOfFile:SEGPicName(@"back")];
    UIButton* leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setImage:image forState:UIControlStateNormal];
    [leftButton setImage:image forState:UIControlStateHighlighted];
    leftButton.imageEdgeInsets = UIEdgeInsetsMake(0, 18, 0, -18);
    [leftButton addTarget:self action:@selector(onNavigationLeftButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.top.mas_equalTo(20+LYSafeAreaTop());
            make.size.mas_equalTo(44);
    }];
    
    [self.otherDoorView hideCloseButton];
}

- (void)creatTab {
    // 添加切换按钮
    UIView *buttonHeaderView = [[UIView alloc] init];
    [self.view addSubview:buttonHeaderView];
    UIView *buttonContainerView = [[UIView alloc] init];
    [buttonHeaderView addSubview:buttonContainerView];
    [buttonContainerView addSubview:self.switchQRCodeButton];
    [buttonContainerView addSubview:self.switchListButton];
    [buttonHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kTopTabAreaHeight-kHeaderViewHeight);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(kHeaderViewHeight);
    }];
    [buttonContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.bottom.mas_equalTo(0);
    }];
    [self.switchQRCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.bottom.mas_equalTo(0);
    }];
    [self.switchListButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.switchQRCodeButton.mas_right).offset(30);
        make.right.mas_equalTo(0);
        make.top.bottom.mas_equalTo(0);
    }];
}

- (void)creatOtherDoorView {
    SEGHAllDoorView *doorView = [[SEGHAllDoorView alloc]initWithFrame:CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight())];
    doorView.clipsToBounds = YES;
    if (self.isFromServerList) {
         [doorView updateTipLabelText:@"长按门禁按钮，拖拽调整排序\n前8个着色按钮将显示在首页"];
    }
    [doorView setCloseBox:^{
        [self dismissViewController];
    }];
    
    //点击问题
    [doorView  setProblemBlock:^{
        SEGOpenDoorNoticeChooseViewController *settingVC = [SEGOpenDoorNoticeChooseViewController new];
        settingVC.isHideBar=YES;
        [self.navigationController pushViewController:settingVC animated:YES];
    }];
    
    [doorView setItemBox:^(SEGNewMyDoorListModel *model) {
        [self openDoor:model];
    }];
    
    [self.view addSubview:doorView];
    CGFloat doorViewTopMargin = self.isHaveTab ? kTopTabAreaHeight : LYSafeAreaTop();
    doorView.totalHeight = LYScreenHeight() - doorViewTopMargin;
    [doorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.isHaveTab ? kTopTabAreaHeight : 0);
    }];
    self.otherDoorView = doorView;
    
    // 在外部已经先请求了门禁数据并缓存，这里直接展示本地缓存数据
    // sany需要对数据进行处理 不展示海康门禁, 不展示微光门
    [self.otherDoorView setDataSource:self.otherDoorList];
}

// 加载一码通行二维码
- (void)loadOneQRCodePassData {
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/door-restapi/v1/userapp/generateQRCodeForDoor",nil];
    NSDictionary *param = @{@"deviceType" : @([self.oneQrcodePassDoor.deviceType integerValue]),
                            @"communityId" : kAccountCommunityID ?: @"",
                            @"tel" : kAccountMobile ?: @"",
                            @"deviceId" : self.oneQrcodePassDoor.deviceid ?: @""
                            };
    WeakSelf;
    [SVProgressHUD show];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:param finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        // codeType 0：成功；-1：失败；2：无门禁权限
        if ([codeType integerValue] == 2) {
            [weakSelf.qrcodeView showNoauthView];
            // 恢复亮度
            [self restoreScreenBrightness];
            return;
        }
        // 二维码不为空则展示
        NSString *QRCodeString = result[@"data"] ?: @"";
        if (isSuccessed && QRCodeString.length > 0) {
            [weakSelf.qrcodeView showQRCodeWithString:QRCodeString];
            // 调高亮度
            [self increaseScreenBrightness];
            return;
        }
        // 其他情况都是加载失败
        [weakSelf.qrcodeView showLoadFailView];
        // 恢复亮度
        [self restoreScreenBrightness];
    }];
}

// 调高屏幕亮度
- (void)increaseScreenBrightness {
    self.isChangedBrightness = YES;
    [[UIScreen mainScreen] setBrightness:1];
}

// 恢复屏幕亮度
- (void)restoreScreenBrightness {
    if (self.isChangedBrightness) {
        [[UIScreen mainScreen] setBrightness:self.currentBrightness];
        self.isChangedBrightness = NO;
    }
}

- (void)onNavigationLeftButtonClicked:(UIButton *)sender {
    [self dismissViewController];
}

- (void)dismissViewController {
    // 恢复亮度
    [self restoreScreenBrightness];
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        if (self.disapperCallback) {
            self.disapperCallback();
        }
    }];
}

-(void)openDoor:(SEGNewMyDoorListModel*)data {
    if (!data) {
        return;
    }
    
    [SEGOpenDoorBussinessManager shareInstance].openSuccessBlock = ^{
        [self dismissViewController];
    };
    
    [[SEGOpenDoorBussinessManager shareInstance] openDoorWithDoorModel:data completeCallback:^(SEGNewOpenDoorModel * _Nonnull data) {
        if (self.completedCallback) {
            self.completedCallback(data);
        }
    }];
}

#pragma mark - action
- (void)switchQRCodeButtonTap:(UIButton *)sender {
    if (!sender.selected) {
        sender.selected = YES;
        sender.titleLabel.font = [UIFont boldSystemFontOfSize:22];
        [sender setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
        
        self.switchListButton.selected = NO;
        self.switchListButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.switchListButton setTitleColor:[UIColor colorWithHexString:@"#9B9B9B"] forState:UIControlStateNormal];
    }
    self.qrcodeView.hidden = NO;
    // 显示二维码的时候 调高屏幕亮度
    if (self.qrcodeView.isShowQrcode) {
        [self increaseScreenBrightness];
    }
}

- (void)switchListButtonTap:(UIButton *)sender {
    if (!sender.selected) {
        sender.selected = YES;
        sender.titleLabel.font = [UIFont boldSystemFontOfSize:22];
        [sender setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
        
        self.switchQRCodeButton.selected = NO;
        self.switchQRCodeButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.switchQRCodeButton setTitleColor:[UIColor colorWithHexString:@"#9B9B9B"] forState:UIControlStateNormal];
    }
    self.qrcodeView.hidden = YES;
    // 恢复屏幕亮度
    [self restoreScreenBrightness];
}

#pragma mark - getter setter
- (UIButton *)switchQRCodeButton {
    if (!_switchQRCodeButton) {
        _switchQRCodeButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTitle:@"一码通行" forState:UIControlStateNormal];
            [button setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont boldSystemFontOfSize:22];
            [button addTarget:self action:@selector(switchQRCodeButtonTap:) forControlEvents:UIControlEventTouchUpInside];
            button.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
            button.selected = YES;
            button;
        });
    }
    return _switchQRCodeButton;
}

- (UIButton *)switchListButton {
    if (!_switchListButton) {
        _switchListButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTitle:@"非扫码门禁" forState:UIControlStateNormal];
            [button setTitleColor:[UIColor colorWithHexString:@"#9B9B9B"] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:13];
            [button addTarget:self action:@selector(switchListButtonTap:) forControlEvents:UIControlEventTouchUpInside];
            button.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
            button;
        });
    }
    return _switchListButton;
}

- (SEGSanyQRCodeView *)qrcodeView {
    if (!_qrcodeView) {
        _qrcodeView = [[SEGSanyQRCodeView alloc] init];
        _qrcodeView.userInteractionEnabled = YES;
    }
    return _qrcodeView;
}

- (SEGDoorListViewModel *)doorListViewModel {
    if (!_doorListViewModel) {
        _doorListViewModel = [SEGDoorListViewModel new];
    }
    return _doorListViewModel;
}

@end
